package cn.tedu.micro.demo.common.service;

import cn.tedu.micro.demo.common.mapper.CartMapper;
import cn.tedu.micro.demo.common.mapper.OrderMapper;
import cn.tedu.micro.demo.common.mapper.StockMapper;
import cn.tedu.micro.demo.common.pojo.po.CartPO;
import cn.tedu.micro.demo.common.pojo.po.OrderPO;
import cn.tedu.micro.demo.common.pojo.po.StockPO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class StockServiceImpl implements StockService{
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Override
    public Boolean submitOrder(Integer userId, String productCode, Integer count) {
//       1扣减库存，库存原1000，count扣减掉
        UpdateWrapper<StockPO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("product_code",productCode);
        updateWrapper.setSql("stock=stock-" + count);
        int update = stockMapper.update(null,updateWrapper);
//        update>0 表示更新成功， 找到了数据，执行了更新
//        1.1判断：扣减成功 继续
//        1。2 判断扣减失败，返回 false
        if (count==0){
            return false;
        }
//        2生成订单 封装orderPO 写入数据库
        OrderPO orderPO = new OrderPO();
        orderPO.setCount(count);
        orderPO.setProductCode(productCode);
        orderPO.setUserId(userId);
//        订单编号，保证唯一，使用uuid
        orderPO.setOrderNo(UUID.randomUUID().toString());
        orderMapper.insert(orderPO);
//        根据userId 和productCode 删除购物车数据
        QueryWrapper<CartPO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("product_code",productCode);
        cartMapper.delete(wrapper);
        return true;
    }
}
